//
//  AppDelegate.m
//  LNDevelopExample
//
//  Created by wwww on 2018/9/4.
//  Copyright © 2018年 淘发现1iOS. All rights reserved.
//

#import "AppDelegate.h"
#import "LNMainViewController.h"
#import "LNNewFeatureViewModel.h"

#if defined(DEBUG)||defined(_DEBUG)
#import <JPFPSStatus/JPFPSStatus.h>
#import "LNDebugTouchView.h"
//#import <FBMemoryProfiler/FBMemoryProfiler.h>
//#import <FBRetainCycleDetector/FBRetainCycleDetector.h>
//#import "CacheCleanerPlugin.h"
//#import "RetainCycleLoggerPlugin.h"
#endif

@interface AppDelegate ()
/// APP管理的导航栏的堆栈
@property (nonatomic, readwrite, strong) LNNavigationControllerStack *navigationControllerStack;
/// APP的服务层
@property (nonatomic, readwrite, strong) LNViewModelServicesImpl *services;
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    /// 初始化UI之前配置
    [self _configureApplication:application initialParamsBeforeInitUI:launchOptions];
    
    // Config Service
    self.services = [[LNViewModelServicesImpl alloc] init];
    // Config Nav Stack
    self.navigationControllerStack = [[LNNavigationControllerStack alloc] initWithServices:self.services];
    // Configure Window
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    // 重置rootViewController
    [self.services resetRootViewModel:[self _createInitialViewModel]];
    // 让窗口可见
    [self.window makeKeyAndVisible];
    
    /// 初始化UI后配置
    [self _configureApplication:application initialParamsAfterInitUI:launchOptions];
    
#if defined(DEBUG)||defined(_DEBUG)
    /// 调试模式
    [self _configDebugModelTools];
#endif
    
    // Save the application version info. must write last
    [[NSUserDefaults standardUserDefaults] setValue:LN_APP_VERSION forKey:LNApplicationVersionKey];
    [[NSUserDefaults standardUserDefaults] synchronize];
    return YES;
}






#pragma mark - 在初始化UI之前配置
- (void)_configureApplication:(UIApplication *)application initialParamsBeforeInitUI:(NSDictionary *)launchOptions
{
    /// 显示状态栏
    [application setStatusBarHidden:NO withAnimation:UIStatusBarAnimationFade];
    
    /// 配置键盘
    [self _configureKeyboardManager];
    
    /// 配置文件夹
    [self _configureApplicationDirectory];
    
    /// 配置FMDB
    [self _configureFMDB];
}

/// 配置文件夹
- (void)_configureApplicationDirectory
{
    /// 创建doc
    //[MHFileManager createDirectoryAtPath:MHWeChatDocDirPath()];
    /// 创建cache
    //[MHFileManager createDirectoryAtPath:MHWeChatCacheDirPath()];
    
    //NSLog(@"MHWeChatDocDirPath is [ %@ ] \n MHWeChatCacheDirPath is [ %@ ]" , MHWeChatDocDirPath() , MHWeChatCacheDirPath());
}

/// 配置键盘管理器
- (void)_configureKeyboardManager {
    IQKeyboardManager.sharedManager.enable = YES;
    IQKeyboardManager.sharedManager.enableAutoToolbar = NO;
    IQKeyboardManager.sharedManager.shouldResignOnTouchOutside = YES;
}

/// 配置FMDB
- (void) _configureFMDB
{
    //    [[FMDatabaseQueue sharedInstance] inDatabase:^(FMDatabase *db) {
    //        NSString *version = [[NSUserDefaults standardUserDefaults] valueForKey:SBApplicationVersionKey];
    //        if (![version isEqualToString:SB_APP_VERSION]) {
    //            NSString *path = [[NSBundle mainBundle] pathForResource:@"senba_empty_1.0.0" ofType:@"sql"];
    //            NSString *sql  = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    //            /// 执行文件
    //            if (![db executeStatements:sql]) {
    //                SBLogLastError(db);
    //            }
    //        }
    //    }];
}

#pragma mark - 在初始化UI之后配置
- (void)_configureApplication:(UIApplication *)application initialParamsAfterInitUI:(NSDictionary *)launchOptions
{
    /// 配置ActionSheet
    [LCActionSheet ln_configureActionSheet];
    
    /// 预先配置平台信息
    //    [SBUMengService configureUMengPreDefinePlatforms];
    
    @weakify(self);
    /// 监听切换根控制器的通知
    [[LNNotificationCenter rac_addObserverForName:LNSwitchRootViewControllerNotification object:nil] subscribeNext:^(NSNotification * note) {
        /// 这里切换根控制器
        @strongify(self);
        // 重置rootViewController
        LNSwitchRootViewControllerFromType fromType = [note.userInfo[LNSwitchRootViewControllerUserInfoKey] integerValue];
        NSLog(@"fromType is  %zd" , fromType);
        /// 切换根控制器
        [self.services resetRootViewModel:[self _createInitialViewModel]];
        
        /// 切换了根控制器，切记需要将指示器 移到window的最前面
#if defined(DEBUG)||defined(_DEBUG)
        [self.window bringSubviewToFront:[LNDebugTouchView sharedInstance]];
#endif
    }];
    
    /// 配置H5
    //    [SBConfigureManager configure];
}

#pragma mark - 调试(DEBUG)模式下的工具条
- (void)_configDebugModelTools
{
    /// 显示FPS
    [[JPFPSStatus sharedInstance] open];
    
    /// 打开调试按钮
    [LNDebugTouchView sharedInstance];
    /// CoderMikeHe Fixed: 切换了根控制器，切记需要将指示器 移到window的最前面
    [self.window bringSubviewToFront:[LNDebugTouchView sharedInstance]];
}



#pragma mark - 创建根控制器
- (LNViewModel *)_createInitialViewModel {
    // The user has logged-in.
    NSString *version = [[NSUserDefaults standardUserDefaults] valueForKey:LNApplicationVersionKey];
    /// 版本不一样就先走 新特性界面
    if (![version isEqualToString:LN_APP_VERSION]){
        return [[LNNewFeatureViewModel alloc] initWithServices:self.services params:nil];
    }else{
         return [[LNMainViewModel alloc] initWithServices:self.services params:nil];
//        /// 这里判断一下
//        if ([SAMKeychain rawLogin] && self.services.client.currentUser) {
//            /// 有账号+有用户数据
//            /// 已经登录，跳转到主页
//            return [[LNHomePageViewModel alloc] initWithServices:self.services params:nil];
//        }else if(self.services.client.currentUser){ /// 没账号+有用户数据
//            /// 跳转到账户登录页面
//            return [[LNAccountLoginViewModel alloc] initWithServices:self.services params:nil];
//        }else{
//            /// 第一次使用微信
//            return [[LNBootLoginViewModel alloc] initWithServices:self.services params:nil];
//        }
    }
}

#pragma mark- 获取appDelegate
+ (AppDelegate *)sharedDelegate{
    return (AppDelegate *)[[UIApplication sharedApplication] delegate];
}
@end
